<template>
  <div id="reagentViewDiv">
    <div class="bodyContent">
      <el-tabs type="border-card">
        <el-tab-pane label="创建视图">
          <Splitpanes class="area">
            <Pane size="60">
              <vxe-toolbar perfect>
                <template #buttons>
                  <vxe-input v-model="searchForm.keyvalue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @keyup="keyupEnter" @clear="findList" @search-click="handleSearch(form)"></vxe-input>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findList"></vxe-button>
                  <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
                </template>
              </vxe-toolbar>
              <vxe-table ref="tableRef" border="inner" align="left" class="mytable-scrollbar" :cell-style="calcCellBgColor" :loading="loading" height="auto" :data="tableData" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }" @current-change="tableCellClick" @menu-click="contextMenuClickEvent">
                <vxe-column type="checkbox" width="26"></vxe-column>
                <vxe-column type="seq" title="#" width="30"></vxe-column>
                <vxe-column field="name" title="名称" width="120"> </vxe-column>
                <vxe-column field="title" title="标题" width="120"> </vxe-column>
                <vxe-column field="viewSource" title="来源" width="60">
                  <template #default="{ row }">
                    <span v-if="row.viewSource==1">数据库</span>
                    <span v-else>系统</span>
                  </template>
                </vxe-column>
                <vxe-column field="viewType" title="类型" width="60">
                  <template #default="{ row }">
                    {{ getmessTypeName(row) }}
                  </template> </vxe-column>
                <vxe-column field="costTime" title="耗时" width="60"> </vxe-column>
                <vxe-column field="applyName" title="申请人" width="100"> </vxe-column>
                <vxe-column field="applyTime" title="申请时间" width="120"> </vxe-column>
                <vxe-column field="auditName" title="审核人" width="100"> </vxe-column>
                <vxe-column field="auditTime" title="审核时间" width="120"> </vxe-column>
                <vxe-column field="content" title="内容"> </vxe-column>
                <vxe-column field="remark" title="功能描述" min-width="150"> </vxe-column>
                <vxe-column field="remark" title="状态" width="80">
                  <template #default="{ row }">
                    <span v-if="row.status==1" style="color:blue;">已审核</span>
                    <span v-else style="color:red;">未审核</span>
                  </template>
                </vxe-column>
              </vxe-table>
            </Pane>
            <Pane size="40">
              <el-divider content-position="left">视图基本信息
              </el-divider>
              <vxe-toolbar perfect ref="toolbarRef">
                <template #buttons>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-add" content="新建" @click="createView"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="预览" @click="testSqlView"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveView('viewFormRef')"></vxe-button>
                </template>
              </vxe-toolbar>
              <el-form ref="viewFormRef" :model="viewForm" :rules="viewFormRule" label-width="100px" class="form-input-m" inline-message>
                <el-form-item prop="title" label="标题">
                  <el-input type="text" v-model="viewForm.title" placeholder="请输入标题" clearable></el-input>
                </el-form-item>
                <el-form-item prop="name" label="名称（SQL）">
                  <el-input type="text" v-model="viewForm.name" placeholder="请输入名称" clearable></el-input>
                </el-form-item>
                <el-form-item prop="viewType" label="类型">
                  <el-select v-model="viewForm.viewType" filterable placeholder="请选择工作组" style="width: 200px">
                    <el-option v-for="messType in viewsTypeList" :key="messType.code" :label="messType.name" :value="messType.code"></el-option>
                  </el-select>
                </el-form-item>
                <!-- <el-form-item prop="viewSource" label="来源">
                  <el-input type="text" v-model="viewForm.viewSource" placeholder="请输入来源" clearable></el-input>
                </el-form-item> -->
                <el-form-item label="功能说明" prop="remark">
                  <el-input v-model="viewForm.remark" placeholder="请输入说明" clearable type="textarea" :autosize="{ minRows: 5, maxRows: 5 }" style="width: 560px"></el-input>
                </el-form-item>
                <el-form-item label="视图内容" prop="content">
                  <el-input v-model="viewForm.content" placeholder="请输入视图内容" clearable type="textarea" :autosize="{ minRows: 10, maxRows: 10 }" style="width: 560px"></el-input>
                </el-form-item>
              </el-form>
              <el-divider content-position="left">测试结果
              </el-divider>
              <div class="tableBody">
                <vxe-table ref="viewTableRef" class="mytable-scrollbar" border height="300px;" align="left" :data="viewList" :loading="showLoading" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }" resizable show-overflow>
                  <vxe-column v-for="item in coloumList" :key="item" :field="item" :title="item" width="120"> </vxe-column>
                </vxe-table>
              </div>
            </Pane>
          </Splitpanes>
        </el-tab-pane>
      </el-tabs>
    </div>

  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { Splitpanes, Pane } from 'splitpanes';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import { isEmpty } from 'lodash';

let showLoading = ref(false); //刷新加载状态

let searchForm = {
  keyvalue: ''
};

// 最左侧 新建/编辑字典分类弹框表单
let viewForm = reactive({
  id: '',
  title: '',
  name: '',
  content: '',
  remark: '',
  status: '',
  viewType: '',
  viewSource: '2'
});

// 最左侧字典分类弹框表单校验
let viewFormRule = {
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ],
  content: [
    {
      required: true,
      message: '请输入内容',
      trigger: 'blur'
    }
  ]
};
let viewList: any = reactive([]);
let coloumList: any = reactive([]);
const tableData = reactive([]); //表格数据
const tableRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记

const viewsTypeList = reactive([]); //表格数据

// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  findList(); //获取样本类型表格数据
  getDictDetailList();
});

function getDictDetailList() {
  viewsTypeList.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'viewTypes' } })
    .then((res: any) => {
      viewsTypeList.push(...res.data);
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function getmessTypeName(row) {
  // proxy.$nextTick(() => {
  if (viewsTypeList.length > 0) {
    const group = viewsTypeList.find((item) => item.code == row.viewType);
    return group ? group.name : '';
  }
}

// 获取 样本类型表格数据
const findList = () => {
  tableData.length = 0; //放入数据前清空数据
  const url = '/view/apply/getViewApplyList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { keyWords: searchForm.keyvalue, viewSource: 2 } })
    .then(async (res: any) => {
      tableData.push(...res.data);
      tableCellClick({ row: res.data[0] });
      const $table = tableRef.value;
      if ($table) {
        await $table.setCurrentRow(res.data[0]);
      }
    })
    .catch((err: any) => {
      VxeMessage('获取视图申请列表数据异常', VxeNotifyType.error);
    });
};

// 表格选中当前行
function tableCellClick({ row }: any) {
  viewList.length = 0; //放入数据前清空数据
  Object.assign(viewForm, row);
  proxy.$forceUpdate();
}

function createView() {
  viewList.legth = 0;
  clearViewForm();
}
function testSqlView() {
  showLoading.value = true;
  const url = '/view/apply/getViewApplyTestResultList';
  viewList.length = 0; //放入数据前清空数据
  coloumList.length = 0;
  proxy.$http
    //注意此处的数据条数
    .post(url, { sql: viewForm.content, id: viewForm.id, name: viewForm.name })
    .then((res: any) => {
      showLoading.value = false;
      coloumList.push(...res.data.coloums);
      viewList.push(...res.data.data);
    })
    .catch((err: any) => {
      showLoading.value = false;
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}

function calcCellBgColor({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  if (row.costTime.replace('ms', '') > 3000) {
    return { background: '#FF9900', color: '#fff' };
  }
}

function saveView(formName: any) {
  const el: any = proxy.$refs[formName];
  el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    let url = '/view/apply/saveViewApply';
    proxy.$http
      .post(url, viewForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('保存成功', VxeNotifyType.success);
          findList();
        }
      })
      .catch((err: any) => {
        VxeMessage('保存异常', VxeNotifyType.error);
      });
  });
}

function clearViewForm() {
  //pnameShow.value = false;
  viewForm.id = '';
  viewForm.title = '';
  viewForm.name = '';
  viewForm.content = '';
  viewForm.remark = '';
  viewForm.status = '';
  viewForm.viewSource = '2';
  viewForm.viewType = '';
}
</script>

<style lang="scss" scoped>
#reagentViewDiv {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    :deep(.el-tabs) {
      height: 100%;

      .el-tabs__content {
        height: calc(100% - 39px);
        padding: 0;

        .el-tab-pane {
          height: 100%;
        }
      }
    }

    .area {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .leftTable {
        height: calc(100% - 39px);
      }

      .el-tabs--border-card {
        border: none;
        height: 100%;

        :deep(.el-tabs__content) {
          height: calc(100% - 39px - 20px);
          padding: 10px;

          .el-tab-pane {
            height: 100%;
          }
        }
      }

      // tab报告单元仪器

      .rptGroupInstrTable {
        height: calc(100% - 24px - 10px);
      }

      .el-radio {
        margin-right: 10px;
      }
    }
  }
}
</style>
